const http  = require('http');
const fs = require('fs');
const querystring = require('queryString');
const urlLib = require('url');
var users = {};
http.createServer((req,res)=>{
    //解析数据
    var str = '';
    obj = urlLib.parse(req.url,true);
    var url = obj.pathname;
    var GET = obj.query;
    var POST = {};
    var obj
    req.on('data',function(data){
        str += data;
    })
    req.on('end',function(){
        POST = querystring.parse(str);
    })
    //读取文件
    if(url=='/user'){//区分是接口还是文件
        switch(GET.act){
            case 'reg':
                //1 检查用户是否已经存在
                if(users[GET.username]){
                    res.write('{"ok":false,"msg":"此用户已存在"}');
                }else{//2 插入
                    users[GET.username] = GET.pwd;
                    res.write('{"ok":true,"msg":"注册成功"}');
                }
                break;
            case 'login':
                //1 检查用户是否存在
                if(users[GET.username]==null){
                    res.write('{"ok":false,"msg":"此用户不存在"}');
                }else if(users[GET.username]!=GET.pwd){//2 检查用户密码是否正确
                    res.write('{"ok":false,"msg":"用户名或密码有误"}');
                }else{
                    res.write('{"ok":true,"msg":"登录成功"}');
                }

                break;
            default:
                res.write('{"ok":false,"msg":"未知的act"}');
        }
        res.end();
    }else{
        var filename = './www'+url;
        fs.readFile(filename,function(err,data){
            if(err){
                res.write('404');
            }else{
                res.write(data);
            }
            res.end();
        })
    }

}).listen(8080);
